<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <!-- 
           {
          id: 7697,
          userId: "84a72a15-8b3a-4021-a8f2-8dd32343447b",
          skuId: 6061,
          cartPrice: 2222,
          skuNum: 3,
          imgUrl:"http://47.93.148.192:8080/group1/M00/00/02/rBHu8l-rgfWAVRWzAABUiOmA0ic932.jpg",
          skuName: "Apple iPhone 12",
          isChecked: 1,
          isOrdered: 0,
          skuPrice: 2222,
        };
         -->
        <ul class="cart-list" v-for="goods in cartInfoList" :key="goods.id">
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked="!goods.isChecked" @change="setGoodsIsChecked(goods)"/>
          </li>
          <!-- 商品 -->
          <li class="cart-list-con2">
            <img :src="goods.imgUrl" />
            <div class="item-msg">
              {{goods.skuName}}
            </div>
          </li>

          <!-- 单价 -->
          <li class="cart-list-con4">
            <span class="price">￥ {{goods.skuPrice}}</span>
          </li>
          <!-- 数量 -->
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="addCountNum(goods,-1)">-</a>
            <input
              autocomplete="off"
              type="text"
              :value="goods.skuNum"
              minnum="1"
              @keyup.enter="handelNum(goods,$event)"
              class="itxt"
            />
            <a href="javascript:void(0)" class="plus" @click="addCountNum(goods,1)">+</a>
          </li>
          <!-- 小计（元）  总价 -->
          <li class="cart-list-con6">
            <span class="sum">{{goods.skuPrice * goods.skuNum}}</span>
          </li>
          <!-- 操作 -->
          <li class="cart-list-con7">
            <a  class="sindelet" @click="showDelCart(goods)">删除 <span class="iconfont icon-shanchu"></span></a>
            <a  class="enshrine">移到收藏 
              <span class="iconfont icon-shoucang shoucang"></span> 
              <span class="iconfont icon-shoucang1 shoucang1"></span>
            </a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <label >
        <input class="chooseAll" type="checkbox" v-model="checkAll"/>
        <span> 全选</span></label>
      </div>
      <div class="option">
        <a href="#none" @click="delAllGoods">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择 <span>{{ isCheckedNum }}</span>件商品</div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <a class="sum-btn" @click="jiesuan">结算</a>
        </div>
      </div>
    </div>
    
    <Dialog :visible.sync="visible" >
      <template v-slot:header>提示</template>
      <template>
        亲！确定要{{isDelCheckedCart ?"移除这些宝贝" : '把这件宝贝移除购物车列表' }}吗？
      </template>
      <template #footer>
        <div class="btn-wrap">
          <button class="btn" @click="cancelBtn">取消</button>
          <button class="btn primary" @click="delGoods">确认</button>
        </div>
      </template>
    </Dialog>

    <Dialog :visible.sync="toTradeVisible">
      <template v-slot:header>
        警告
      </template>
      <template>
        你没有选择要结算的商品！
      </template>
    </Dialog>
  </div>
</template>

<script>
import debounce from "lodash/debounce"
import Dialog from "@/components/Dialog"
import { reqGetCarlist ,reqDeleteCart,reqAddToCart} from "@/api";
export default {
  name: "ShopCart",
  data() {
    return {
      cartInfoList: [],
      visible:false,
      toTradeVisible:false,
      willDelGoods:null,
      isDelCheckedCart: false,
      changedNums:0
    };
  },
  async mounted() {
    // vue validate
    const list = await reqGetCarlist();
    
    this.cartInfoList = list[0] ? list[0].cartInfoList : [];
  },
  methods:{
    setGoodsIsChecked(goods){//每个商品的勾选函数
      //"1"表示未勾选，0表示勾选
      goods.isChecked = 1 - goods.isChecked
      
    },
    addCountNum(goods,num){ //每个商品数量增加+1,或减少-1
      
      if(num === -1 && goods.skuNum>1){
        goods.skuNum--
        this.changedNums--
      } 
       if(num === 1) {
         goods.skuNum++
         this.changedNums++
       }
      //用防抖包起来
      this.changeCart(goods.skuId,this.changedNums)
    } ,
    //用防抖函数发送请求，更新商品数量
    changeCart:debounce(async function(skuId,num){
      if(this.changedNums === 0) return
      this.changedNums = 0
      await reqAddToCart(skuId,num)
    },1000) ,
      
    handelNum(goods,e){
        const value= e.target.value.trim()/1
        
        //输入的不是数字,或者小于1
        if(Number.isNaN(value) || value < 1) {
          
          goods.skuNum =1
          return}

        if(value >100){
          goods.skuNum = 100
          return
        } 
        goods.skuNum = value

      },
    async delGoods(){ //删除单个或多个
      // 判断是否删除多个
      if(this.isDelCheckedCart){
        this.cartInfoList = this.cartInfoList.filter(goods =>{
          if(goods.isChecked === 0) {
            reqDeleteCart(goods.skuId)
          }
          return  !!goods.isChecked
        })

        this.visible = false
        this.isDelCheckedCart =false
        return
      }

      //删除单个选中的商品
      //找到索引
      const index =  this.cartInfoList.findIndex(g => g === this.willDelGoods )
      this.cartInfoList.splice(index ,1)
      this.visible = false
      await reqDeleteCart(this.willDelGoods.skuId)
    
    },
    delAllGoods(){
      //弹出模态框
      this.visible = true
      this.isDelCheckedCart =true  
    },
    cancelBtn(){ //模态框取消按钮
      this.visible = false
      this.isDelCheckedCart =false
    },
    showDelCart(goods){//点击删除显示提示模态框
      this.visible = true
      this.willDelGoods=goods
    },
    jiesuan(){//结算按钮
      //判断有没有勾选商品
      if(this.isCheckedNum === 0){
        this.toTradeVisible = true
        return
      } 
      this.$router.push("/trade")
    }
  },
  computed:{
    isCheckedNum(){//选中的商品的数量
      return this.cartInfoList.reduce((p,c)=>{
        return p+ (c.isChecked === 0? c.skuNum:0)
      },0)
    },
    totalPrice(){ //选中的商品的总价
      return this.cartInfoList.reduce((p,c)=>{
        return p + (c.isChecked===0 ? c.cartPrice*c.skuNum : 0)
      },0)
    },
    checkAll:{
      get(){ //购物车全选
        if(!this.cartInfoList.length) return
        return this.cartInfoList.every(good => good.isChecked === 0  )
      },
      set(newcheck){
        const isChecked = newcheck ? 0:1
        
        this.cartInfoList.forEach(goods =>{
          //不改
          if(goods.isChecked === isChecked) return
          goods.isChecked = isChecked 
          
        })
      }
    }
  },
  components:{
    Dialog,
  }
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      & > div {
        float: left;
      }

      .cart-th1 {
        width: 15%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 34%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        & > li {
          float: left;
        }

        .cart-list-con1 {
          width: 4.1667%;
        }

        .cart-list-con2 {
          width: 45%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con3 {
          width: 20.8333%;

          .item-txt {
            text-align: center;
          }
        }

        .cart-list-con4 {
          width: 12.5%;
          font-size: 14px;
        }
        .price,
        .sum {
          color: rgb(248, 51, 51);
          
        }
        .cart-list-con5 {
          width: 12.5%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          a{
            text-decoration: none;
          }
        }

        .cart-list-con6 {
          width: 12.5%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 12.5%;
          a {
            display: block;
            margin:10px ;
            color: #666;
            
            text-decoration: none;
            cursor: pointer;
            // &:hover{
            //   color: rgb(255, 42, 42);
            // }
          }
          .shoucang1{
            display: none;
          }
          .sindelet:hover{
            color: rgb(255, 42, 42);
          }
          .enshrine:hover {
            color: rgb(219, 68, 68);
            .shoucang{
              display: none;
            }
            .shoucang1{
              display: inline;
            }
          }
          
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;text-decoration: none;
        }

      }
    }
  }
}
.btn-wrap {
  float: right;
}
.btn {
  font-size: 12px;
  border: 1px solid #ccc;
  padding: 8px 15px;
  border-radius: 3px;
  outline: none;
  background: #fff;
  margin-left: 10px;
  cursor: pointer;
  &.primary {
    border: 1px solid #179ed3;
    background: #179ed3;
    color: #fff;
  }
}

</style>